package com.jse.util.concurrent.new1.executor;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class ExcutorsTest {

	/**
	 * CallableTask返回值测试
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	@Test
	public void testFixedThreadPool() throws InterruptedException, ExecutionException {
		ExecutorService executor = Executors.newFixedThreadPool(5);
		Future<String> future = executor.submit(new CallableTask());
		System.out.println(future.get());
	}
	
	/**
	 * FIFO
	 * @throws Exception
	 */
	@Test
	public void testBeyondSize() throws Exception {
		ExecutorService executor = Executors.newFixedThreadPool(1);
		for (int i = 0; i < 5; i++) {
			executor.execute(new PrintTask("thread-" + i));
		}
		Thread.sleep(5000);
	}
	
	/**
	 * FIFO有序执行, 使用SingleThreadExecutor
	 */
	@Test
	public void testFifoPrint() throws Exception {
		ExecutorService executor = Executors.newSingleThreadExecutor();
		for (int i = 0; i < 3; i++) {
			executor.execute(new PrintTask("Thread-" + i));
		}
		
		new CountDownLatch(1).await(4000, TimeUnit.MILLISECONDS);
	}

	/**
	 * 测试缓存线程池
	 */
	@Test
	public void testThreadPoolExecutor() {
		ExecutorService poolExecutor = Executors.newCachedThreadPool();
		poolExecutor.execute(new MyTask());
	}

	@Test
	public void testScheduledThreadPoolExecutor() throws Exception {
		ScheduledExecutorService executor = Executors
				.newScheduledThreadPool(10);
		executor.schedule(new MyTask(), 4, TimeUnit.SECONDS);

		Thread.sleep(5000);
	}
}

class MyTask implements Runnable {
	@Override
	public void run() {
		System.out.println("this is my task");
	}
}

class CallableTask implements Callable<String> {

	@Override
	public String call() throws Exception {
		// TODO Auto-generated method stub
		return "this is callableTask";
	}
}

class PrintTask implements Runnable {
	private String taskName;
	
	public PrintTask(String taskName) {
		this.taskName = taskName;
	}
	
	@Override
	public void run() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(taskName);
	}
}